import { MCPServer } from '../lib/mcp-sdk.js';
import { serverConfig } from '../config/server.config.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs/promises';
import winston from 'winston';

// 设置日志
const logger = winston.createLogger({
  level: serverConfig.logging.level,
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: serverConfig.logging.filename }),
    new winston.transports.Console()
  ]
});

// 获取当前文件的目录
const __dirname = dirname(fileURLToPath(import.meta.url));

class MCPDemoServer {
  constructor() {
    this.setupLogger();
    this.server = new MCPServer(serverConfig);
    this.setupHandlers();
  }

  // 设置日志记录器
  setupLogger() {
    this.logger = winston.createLogger({
      level: serverConfig.logging.level,
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
      ),
      transports: [
        new winston.transports.File({ 
          filename: serverConfig.logging.filename 
        }),
        new winston.transports.Console()
      ]
    });
  }

  // 设置请求处理器
  setupHandlers() {
    // 注册文件资源处理器
    this.server.registerResourceHandler('file', async (path) => {
      try {
        const content = await fs.readFile(path, 'utf-8');
        this.logger.info(`成功读取文件: ${path}`);
        return { content };
      } catch (error) {
        this.logger.error(`读取文件失败: ${error.message}`);
        throw new Error(`无法读取文件: ${error.message}`);
      }
    });

    // 注册文本处理工具
    this.server.registerTool('processText', async ({ text, operation }) => {
      this.logger.info(`处理文本，操作: ${operation}`);
      try {
        switch(operation) {
          case 'wordCount':
            return { count: text.split(/\s+/).length };
          case 'charCount':
            return { count: text.length };
          case 'toUpperCase':
            return { text: text.toUpperCase() };
          default:
            throw new Error('不支持的操作');
        }
      } catch (error) {
        this.logger.error(`文本处理失败: ${error.message}`);
        throw error;
      }
    });

    // 注册计算工具
    this.server.registerTool('calculate', async ({ operation, numbers }) => {
      this.logger.info(`执行计算，操作: ${operation}`);
      try {
        if (!Array.isArray(numbers)) {
          throw new Error('numbers必须是数组');
        }

        switch(operation) {
          case 'sum':
            return { 
              result: numbers.reduce((a, b) => a + b, 0),
              operation: '求和'
            };
          case 'average':
            return { 
              result: numbers.reduce((a, b) => a + b, 0) / numbers.length,
              operation: '平均值'
            };
          case 'max':
            return { 
              result: Math.max(...numbers),
              operation: '最大值'
            };
          case 'min':
            return { 
              result: Math.min(...numbers),
              operation: '最小值'
            };
          default:
            throw new Error('不支持的计算操作');
        }
      } catch (error) {
        this.logger.error(`计算失败: ${error.message}`);
        throw error;
      }
    });
  }

  // 启动服务器
  async start() {
    try {
      await this.server.start();
      this.logger.info(`MCP服务器已启动，监听端口 ${serverConfig.port}`);
    } catch (error) {
      this.logger.error(`服务器启动失败: ${error.message}`);
      throw error;
    }
  }
}

// 创建并启动服务器
const server = new MCPDemoServer();
server.start().catch(error => {
  console.error('服务器错误:', error);
  process.exit(1);
}); 